package com.cn.mybatis;

import com.cn.mybatis.dao.IOrderDao;
import com.cn.mybatis.dao.IUserDao;
import com.cn.mybatis.dao.UserMapper;
import com.cn.mybatis.pojo.OrderBean;
import com.cn.mybatis.pojo.UserBean;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.ListResourceBundle;

public class MybatisTest {

    private SqlSession sqlSession;

    @Before
    public void before(){
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            this.sqlSession = sqlSessionFactory.openSession(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void addUser(){
        UserBean userBean = new UserBean();
        userBean.setId(5);
        userBean.setUsername("张三");

        IUserDao mapper = sqlSession.getMapper(IUserDao.class);
        mapper.add(userBean);
    }

    //  mybatis注解@One  一对一映射关系
    @Test
    public void OneToOne(){

        int id = 1;
        IOrderDao mapper = sqlSession.getMapper(IOrderDao.class);
        List<OrderBean> oneToOne = mapper.getOneToOne(1);
        for (OrderBean o: oneToOne) {
            System.out.println(o);
        }

    }
    //  mybatis注解@One  一对多映射关系
    @Test
    public void OneToMany(){
        IUserDao mapper = sqlSession.getMapper(IUserDao.class);
        List<UserBean> list = mapper.getList();

        for (UserBean userBean : list){
            System.out.println(userBean);
        }
    }
    //  mybatis注解@Many  多对多映射关系
    @Test
    public void ManyToMany(){
        IUserDao mapper = sqlSession.getMapper(IUserDao.class);
        List<UserBean> list = mapper.getListAndRole();

        for (UserBean userBean : list){
            System.out.println(userBean);
        }
    }

    //  分页插件
    @Test
    public void pageHelperTest(){

        IUserDao mapper = sqlSession.getMapper(IUserDao.class);

        PageHelper.startPage(1,2);
        List<UserBean> list = mapper.getListAndRole();
        PageInfo<UserBean> pageInfo = new PageInfo<>(list);

        for (UserBean userBean : list){
            System.out.println(userBean);
        }
    }

    @Test
    public void mapperTest(){
        UserBean userBean = new UserBean();
        userBean.setId(5);

        UserMapper u = sqlSession.getMapper(UserMapper.class);
        UserBean u1 = u.selectOne(userBean);
        System.out.println(u1);

    }

}
